package service

import (
	"log"
	"time"

	"github.com/bluele/gcache"
	"github.com/go-redis/redis/v7"
)

type CacheI struct {
	redis *redis.Client
	cache gcache.Cache
}

func initCache() *CacheI {
	switch Conf.Cache.Use {
	case "local":
		return &CacheI{
			redis: nil,
			cache: gcache.New(1024 * Conf.Cache.Memory).LRU().Build(), // Use 1MB Memory
		}
	case "redis":
		if Redis == nil {
			log.Panicln("redis初始化连接失败")
		}

		Log.Info("redis缓存初始化成功")
		return &CacheI{
			redis: Redis,
			cache: nil,
		}
	default:
		Log.Sugar().Debugf("错误的缓存: %s", Conf.Cache.Use)
	}
	return nil
}

func (c *CacheI) Get(s interface{}) (r interface{}, err error) {
	switch Conf.Cache.Use {
	case "local":
		r, err = c.cache.Get(s)
	case "redis":
		err = c.redis.Get(s.(string)).Scan(&r)
	}
	return
}

func (c *CacheI) Set(k string, v interface{}, exp time.Duration) (err error) {
	switch Conf.Cache.Use {
	case "local":
		err := c.cache.SetWithExpire(k, v, exp)
		if err != nil {
			Log.Sugar().Errorf("本地缓存写入异常: %+v", err.Error())
		}
	case "redis":
		sc := c.redis.Set(k, v, exp)
		err = sc.Err()
	}
	return
}

func (c *CacheI) Del(keys ...string) {
	switch Conf.Cache.Use {
	case "local":
		for _, key := range keys {
			c.cache.Remove(key)
		}
	case "redis":
		c.redis.Del(keys...)
	}
	return
}
